package com.alter.global.base.article.service.impl;

import java.util.Calendar;
import java.util.List;

import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alter.global.base.ArticleSearchVO;
import com.alter.global.base.article.dao.AfAriticleTypeDao;
import com.alter.global.base.article.dao.AfArticleDao;
import com.alter.global.base.article.dao.AfTagDao;
import com.alter.global.base.article.service.ArticleCenterService;
import com.alter.model.AfArticle;
import com.alter.model.AfPersonalArticleType;
import com.alter.model.AfTag;
import com.alter.model.SeUser;
import com.alter.orm.Page;
import com.alter.utils.web.HTMLUtil;

@Service("articleCenterService")
@Transactional
public class ArticleCenterServiceImpl implements ArticleCenterService {
    
    /**
     * 文章简讯大小。 当然可以使用系统配置 @Value
     */
    public static final int ARTICLE_BRIEF_SIZE = 250;

    @Autowired
    private AfArticleDao articleDao;
    @Autowired
    private AfTagDao tagDao;
    @Autowired
    private AfAriticleTypeDao articleTypeDao;

    @Override
    public void createArticle(AfArticle article, String context, List<AfTag> tags) {
	// tags
	List<AfTag> articleTag = article.getTags();
	for (AfTag tag : tags) {
	    AfTag _tag = tagDao.saveorupdate(tag);
	    if (!articleTag.contains(_tag)) {
		articleTag.add(_tag);
	    }
	}
	article.setBrief(HTMLUtil.createBrief(context, ARTICLE_BRIEF_SIZE));
	article.setCreate_date(Calendar.getInstance().getTime());
	article.setIsEnabled(Boolean.TRUE);
	articleDao.save(article, context);
    }

    @Override
    public Page<AfArticle> find(ArticleSearchVO searchVO) {
	Page<AfArticle> page = articleDao.searchArticle(searchVO);
	List<AfArticle> list = page.getResult();
	for (AfArticle afArticle : list) {
	    afArticle.setTags(tagDao.searchTagsByArticleAid(afArticle.getAid()));
	}
	return page;
    }

    @Override
    public AfArticle findByAid(String aid) {
	AfArticle article = articleDao.get(aid);
	article.setTags(tagDao.getTags(article.getAid()));
	return article;
    }

    @Override
    public List<AfPersonalArticleType> searchAriticleTypesByUser(SeUser user) {
	return articleTypeDao.find(Restrictions.eq("user.aid", user.getAid()));
    }

}
